By definition, a dictionary cannot hold the same key multiple times. When instantiating a dictionary literal, if a key is repeated, only the last
occurrence of the key will be retained.
This can lead to errors and confusion, as it is not clear which value belongs to which key. This can be remedied by either:
- replacing the duplicated key with the correct key to prevent bugs and errors from occurring later in the program.
- removing the duplicated key to make the code more concise and easier to maintain.
Code examples
Noncompliant code example
{"one": 1, "two": 2, "one": 3} # Noncompliant: the key "one" is duplicated.
def func(a1, a2):
{a1: 1, a2: 2, a1: 3} # Noncompliant: the key a1 is duplicated.
Compliant solution
{"one": 1, "two": 2, "three": 3}
def func(a1, a2):
{a1: 1, a2: 2}